<template>
  <div class="settle-manage">
<!--     <div v-if="!enterpriseId" class="empty-state">
      <p>请选择左侧企业查看对应的对象费用明细</p>
    </div>

    <div v-else> -->
    <div>
      <!-- 搜索筛选 -->
      <el-form :inline="true" :model="headerForm">
        <el-form-item label="所属商户" class="form-item-wrapper">
          <el-select v-model="headerForm.tenantId" placeholder="请选择所属商户" clearable style="width: 180px"
            @change="loadLocationData" filterable remote :remote-method="searchMerchant">
            <el-option v-for="item in merchantList" :key="item.id" :label="item.tenantName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="所在地点位置" class="form-item-wrapper">
          <el-tree-select v-model="headerForm.locationIds" :data="fullLocationTree" multiple collapse-tags collapse-tags-tooltip 
            :render-after-expand="false" show-checkbox :filter-node-method="filterNodeMethod" filterable node-key="id"
            value-key="id" :props="locationTreeProps" @check="loadEnterpriseData" 
            placeholder="请选择所在地点位置" clearable style="width: 180px" />
        </el-form-item>
        <el-form-item label="企业简称" class="form-item-wrapper">
          <el-select v-model="headerForm.enterpriseIds" multiple collapse-tags collapse-tags-tooltip clearable
            placeholder="请选择企业简称" style="width: 185px" filterable remote :remote-method="searchEnterprise">
            <el-option v-for="item in enterpriseList" :key="item.id" :label="item.shortName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="对象类型" class="form-item-wrapper">
          <el-select v-model="headerForm.objectType" placeholder="请选择对象类型" clearable style="width: 150px">
            <el-option label="全部" value="" />
            <el-option label="电表" value="电表" />
            <el-option label="水表" value="水表" />
            <el-option label="房租" value="房租" />
          </el-select>
        </el-form-item>
        <el-form-item label="账期" class="form-item-wrapper">
          <el-input v-model="headerForm.currentBillPeriod" placeholder="请输入账期，如：2024-01" clearable
            style="width: 200px" />
        </el-form-item>
        <el-form-item label="开始日期" class="form-item-wrapper">
          <el-date-picker v-model="headerForm.startDate" type="date" clearable format="YYYY-MM-DD"
            value-format="YYYY-MM-DD" placeholder="选择开始日期" style="width: 130px" />
        </el-form-item>
        <el-form-item label="结束日期" class="form-item-wrapper">
          <el-date-picker v-model="headerForm.endDate" type="date" clearable format="YYYY-MM-DD"
            value-format="YYYY-MM-DD" placeholder="选择结束日期" style="width: 130px" />
        </el-form-item>
        <el-form-item label="结算单明细ID" class="form-item-wrapper">
          <el-input type="number" v-model="headerForm.settleBillDetailId" placeholder="请输入结算单明细ID" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            查询
          </el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 操作按钮 -->
      <div style="margin-bottom: 15px;">
        <el-button type="primary" :disabled="selectedRows.length === 0" @click="handleBatchConfirm" v-if="settlePermissions">
          批量确认
        </el-button>
        <span style="margin-left: 10px; color: #909399; font-size: 14px;">
          已选择 {{ selectedRows.length }} 条
        </span>
      </div>

      <!-- 结算单列表 -->
      <el-table ref="tableRef" :data="tableData.list" highlight-current-row stripe row-key="id" style="width: 100%"
        @selection-change="handleSelectionChange" v-loading="loading" class="scroll-box" :max-height="tableMaxHeight">
        <el-table-column type="selection" width="40" header-align="center" align="center" :selectable="isSelectable" />
        <el-table-column prop="shortName" header-align="center" label="企业简称" />
        <el-table-column prop="objectName" label="对象名称" />
        <el-table-column prop="objectNum" label="对象编号" header-align="center" width="150" />
        <el-table-column prop="objectType" label="对象类型" header-align="center" align="center" width="80" />
        <el-table-column prop="currentBillPeriod" label="账期" header-align="center" min-width="110" />
        <el-table-column prop="startDate" label="开始日期" header-align="center" align="center" min-width="100" />
        <el-table-column prop="endDate" label="结束日期" header-align="center" align="center" min-width="100" />
        <el-table-column label="实际用量" min-width="80">
          <template #default="{ row }">{{ row.actualUsage }}{{ getUsageUnit(row.objectType) }}</template>
        </el-table-column>
        <el-table-column label="当期用量" min-width="80">
          <template #default="{ row }">{{ row.currentUsage }}{{ getUsageUnit(row.objectType) }}</template>
        </el-table-column>
        <el-table-column label="上期用量" min-width="80">
          <template #default="{ row }">{{ row.previousUsage }}{{ getUsageUnit(row.objectType) }}</template>
        </el-table-column>
        <el-table-column label="计费单价" min-width="80">
          <template #default="{ row }">{{ row.unitPrice }}元</template>
        </el-table-column>
        <el-table-column label="费用金额" min-width="80">
          <template #default="{ row }">{{ row.feeAmount }}元</template>
        </el-table-column>
        <el-table-column label="分摊比例" min-width="80">
          <template #default="{ row }">{{ row.allocationRatio }}%</template>
        </el-table-column>
        <el-table-column header-align="center" align="center" label="确认状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.confirmStatus === 1 ? 'success' : 'warning'" size="small">
              {{ row.confirmStatus === 1 ? '已确认' : '待确认' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" header-align="center" align="center" min-width="95">
          <template #default="{ row }">
            <el-button v-if="settlePermissions && row.confirmStatus === 0" type="primary" link @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button v-if="settlePermissions && row.confirmStatus === 0" type="success" link @click="handleConfirm(row)">
              确认
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="pagination-container">
        <Pagination :pageProps="pageProps" layout="prev, pager, next" @search="getList" style="margin-top: 10px;" />
      </div>
    </div>
  </div>
</template>

<script setup lang='ts'>
import { reactive, ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { EnterpriseTreeNode } from '@/api/types/enterprise';
import type { ObjectFeeDetailResult } from '@/api/types/objectFeeDetail';
import Pagination from "@/components/Pagination/Index.vue";
import { 
  getObjectFeeDetailList, updateObjectFeeDetail, confirmObjectFeeDetail,
  getMerchantByName, getLocationTree, getEnterpriseList, getSettlePermissions } from '@/api/settle';
import { isPositiveFloat } from "@/utils/validate";
import { LocationTreeNode } from '@/api/types/location'
import { getUsageUnit } from '@/utils/index';

const loading = ref(false)
const enterpriseId = ref(0);
const tableRef = ref();
const selectedRows = ref<any[]>([]);
const tableMaxHeight = ref(0);
// 结算操作权限
const settlePermissions = ref(false);

const headerForm = reactive({
  tenantId: null,
  locationIds: [],
  enterpriseIds: [],
  currentBillPeriod: "",
  startDate: "",
  endDate: "",
  objectType: "",
  settleBillDetailId: null,
});

const pageProps = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0,
});

const tableData = reactive({
  list: [] as ObjectFeeDetailResult[],
});

const updateData = (enterprise: EnterpriseTreeNode) => {
  enterpriseId.value = enterprise.id;
  getList();
};

// 商户列表
const merchantList = ref<any[]>([]);

// 获取商户列表
const getMerchantList = (name?: string) => {  
  // 使用新的按名称查询接口
  getMerchantByName(name).then((res: any) => {
    if (res.success && res.data) {
      merchantList.value = Array.isArray(res.data) ? res.data : []
    } else {
      console.warn('未获得到商户列表:', res)
      merchantList.value = []
    }
  }).catch((err: any) => {
    console.error('获取商户列表失败', err)    
  })
};

const searchMerchant = (name: string) => {
  getMerchantList(name)
}

// 地点位置数据
const fullLocationTree = ref<LocationTreeNode[]>([])
const locationTreeProps = ref({
  label: 'name'
});

// 加载地点位置数据
const loadLocationData = async () => {
  try {
    if (!headerForm.tenantId) {
      fullLocationTree.value = []
      return
    }
    enterpriseList.value = []
    loadEnterpriseData()
    
    const res = await getLocationTree(headerForm.tenantId)
    if (res.success && res.data) {
      fullLocationTree.value = res.data
    } else {
      const errorMsg = res.msg || '加载地点位置数据失败'
      ElMessage.error(`加载失败: ${errorMsg}`)
      fullLocationTree.value = []
    }
  } catch (error) {
    ElMessage.error('网络请求失败，请检查网络连接后重试')
    fullLocationTree.value = []
  }
}

const filterNodeMethod = (value: string, data: any) => {
  return value ? data.name.includes(value) : true;
}

// 企业列表
const enterpriseList = ref<any[]>([]);

// 加载企业数据
const loadEnterpriseData = async () => {
  let requestData = {
    tenantId: headerForm.tenantId,
    locationIds: headerForm.locationIds,
  }
  doGetEnterpriseList(requestData)
}

// 搜索企业数据
const searchEnterprise = async (shortName: string) => {
  let requestData = {
    shortName: shortName,
    tenantId: headerForm.tenantId,
    locationIds: headerForm.locationIds,
  }
  doGetEnterpriseList(requestData)
}

const doGetEnterpriseList = (requestData: any) => {
  getEnterpriseList(requestData).then((res: any) => {
    if (res.success && res.data) {
      enterpriseList.value = Array.isArray(res.data) ? res.data : []
    } else {
      enterpriseList.value = []
    }
  }).catch((err: any) => {
    console.error('获取企业列表失败', err)
  })
}

const getList = () => {
  //if (!enterpriseId.value) return;
  loading.value = true
  getObjectFeeDetailList({
    enterpriseIds: headerForm.enterpriseIds,
    locationIds: headerForm.locationIds,
    tenantId: headerForm.tenantId,
    currentBillPeriod: headerForm.currentBillPeriod || undefined,
    startTime: headerForm.startDate || undefined,
    endTime: headerForm.endDate || undefined,
    objectType: headerForm.objectType || undefined,
    settleBillDetailId: headerForm.settleBillDetailId,
    pageNum: pageProps.value.pageNum,
    pageSize: pageProps.value.pageSize
  }).then((response) => {
    loading.value = false
    if (response.success) {
      const data = response.data;
      tableData.list = data.records || [];
      pageProps.value.total = data.total || 0;
    } else {
      ElMessage.error(response.msg || '获取数据失败');
      tableData.list = [];
      pageProps.value.total = 0;
    }
  }).catch((error) => {
    loading.value = false
    ElMessage.error('获取数据失败，请稍后重试');
    tableData.list = [];
    pageProps.value.total = 0;
  });
};

const handleSearch = () => {
  pageProps.value.pageNum = 1;
  getList();
};

const resetFilter = () => {
  Object.assign(headerForm, {
    tenantId: null,
    locationIds: [],
    enterpriseIds: [],
    currentBillPeriod: "",
    startDate: "",
    endDate: "",
    objectType: "",
    settleBillDetailId: null,
  });
  Object.assign(pageProps.value, {
    pageNum: 1,
    pageSize: 10,
    total: 0,
  });
  getList();
};

// 复选框选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection;
};

// 编辑
const handleEdit = (row: any) => {
  ElMessageBox.prompt(`请修改当期用量，单位：${getUsageUnit(row.objectType)}`, `编辑当期用量`, {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputValue: row.currentUsage,
    inputPattern: /\S+/, inputErrorMessage: '当期用量不能为空'
  }).then(({ value }) => {
    if (!isPositiveFloat(value)) {
      ElMessage.error('当期用量必须是数字');
      return;
    }
    let requestData = {
      id: row.id,
      currentUsage: value
    }
    updateObjectFeeDetail(requestData)
      .then((res: any) => {
        ElMessage.success("修改成功！");
        getList();
      })
      .catch((err: any) => {
        console.error("err", err.msg);
        ElMessage.error("修改失败！");
      });
  });
};

// 确认
const handleConfirm = async (row: any) => {
  if (!row.id) {
    ElMessage.error('对象费用明细ID不存在');
    return;
  }

  ElMessageBox.confirm(
    `确认该对象费用明细？\n对象：${row.objectName}\n账期：${row.currentBillPeriod}\n金额：${row.feeAmount}元`,
    '确认对象费用明细',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      let requestData = {
        idList: [row.id],
      }
      confirmObjectFeeDetail(requestData)
        .then((res: any) => {
          ElMessage.success("确认成功！");
          getList();
        })
        .catch((err: any) => {
          console.error("err", err.msg);
          ElMessage.error("确认失败！");
        });
    })
    .catch((err: any) => {
      console.error("确认对象费用明细失败:", err);
    });
};

// 批量确认
const handleBatchConfirm = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一条记录');
    return;
  }

  ElMessageBox.confirm(
    `确认选中的 ${selectedRows.value.length} 条对象费用明细？`,
    '批量确认对象费用明细',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      let idList = selectedRows.value.map((item: any) => item.id);
      let requestData = {
        idList: idList,
      }
      confirmObjectFeeDetail(requestData)
        .then((res: any) => {
          ElMessage.success("批量确认成功！");
          getList();
        })
        .catch((err: any) => {
          console.error("err", err.msg);
          ElMessage.error("批量确认失败！");
        });
    })
    .catch((err: any) => {
      console.error("批量确认对象费用明细失败:", err);
    });
};

// 控制哪些行可以选择
const isSelectable = (row: any, index: number) => {
  return row.confirmStatus === 0
}

onMounted(() => {
  tableMaxHeight.value = window.innerHeight - 300;
  
  getSettlePermissions()
  .then((res: any) => {
    if (res.success) {
      settlePermissions.value = res.data;
    } else {
      console.error("获取结算操作权限失败", res.msg);
    }
  })
  .catch((err: any) => {
    console.error("err", err.msg);
  });
});

defineExpose({
  updateData,
  getList
});

</script>

<style lang="scss" scoped>
.scroll-box {
  flex: 1;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
}
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 400px;
  color: #909399;

  p {
    margin: 0;
    font-size: 14px;
    text-align: center;
    line-height: 1.5;
  }
}

// 移除表格边框
:deep(.el-table) {
  .el-table__cell {
    border-right: none !important;
  }

  .el-table__border-left-patch,
  .el-table__fixed-right-patch {
    display: none;
  }
}

.form-item-wrapper {
  margin-right: 10px;
}
</style>